using Microsoft.EntityFrameworkCore;
using MinimalistFoodStreet.BackEnd.Infrastructure.Attributes;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Request.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response;
using MinimalistFoodStreet.BackEnd.Infrastructure.Dtos.Response.Tables;
using MinimalistFoodStreet.BackEnd.Infrastructure.EFCore;
using MinimalistFoodStreet.BackEnd.Server.Server.RequestExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.Server.ResponseExtend.Tables;
using MinimalistFoodStreet.BackEnd.Server.IServer.Tables;
using System.ComponentModel.Design.Serialization;

namespace MinimalistFoodStreet.BackEnd.Server.Server.Tables
{
    [InjectClass]
    public class DictionarysServer : IDictionarysServer
    {
        private readonly ServerRepository _serverRepository;
        public DictionarysServer(DbContext dbContext)
        {
            _serverRepository = new ServerRepository(dbContext);
        }

        public async Task<ResponseApiDto> AddAsync(RequestCreateDictionarysDto dto)
        {
            if (await _serverRepository.dictionarysEFCore.Query(d => d.DValue == dto.value && d.DParentId == dto.parentId && d.DDictionaryTypeId == dto.dictionaryTypeId).AnyAsync())
            {
                return ResponseApiDto.Fail($"该值\"{dto.value}\"已存在");
            }
            int affectedRows = await _serverRepository.dictionarysEFCore.AddAsync(dto.ToCreateEntity());
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> UpdateAsync(RequestUpdateDictionarysDto dto)
        {
            if (await _serverRepository.dictionarysEFCore.Query(d => d.DValue == dto.value && d.DId == dto.id).AnyAsync())
            {
                return ResponseApiDto.Fail($"该值\"{dto.value}\"已存在");
            }
            Dictionary dictionary = await _serverRepository.dictionarysEFCore.Query(d => d.DId == dto.id).SingleOrDefaultAsync();
            if (dictionary == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            dictionary.DValue = dto.value;
            int affectedRows = await _serverRepository.dictionarysEFCore.UpdateAsync(dictionary);
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DeleteAsync(RequestDeleteDictionarysDto dto)
        {
            int childrenCount = await _serverRepository.dictionarysEFCore.Query(d => d.DParentId == dto.id).CountAsync();
            if (childrenCount > 0)
            {
                return ResponseApiDto.Fail($"不能删除有子级的字典，子级数：{childrenCount}");
            }
            int affectedRows = await _serverRepository.dictionarysEFCore.Query(d => d.DId == dto.id).ExecuteDeleteAsync();
            if (affectedRows == 0)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Create(affectedRows);
        }

        public async Task<ResponseApiDto> DetailAsync(int id)
        {
            Dictionary dictionary = await _serverRepository.dictionarysEFCore.Query(d => d.DId == id).SingleOrDefaultAsync();
            if (dictionary == null)
            {
                return ResponseApiDto.Fail("该实例不存在");
            }
            return ResponseApiDto.Ok("数据已获取", dictionary.ToResponseDto());
        }

        public async Task<ResponseApiDto> PaginationAsync(int page, int limit, string? key)
        {
            int total = 0;
            List<Dictionary> dictionarys = await _serverRepository.dictionarysEFCore.Pagination(d => true, false, d => d.DId, out total, page, limit).ToListAsync();
            List<ResponseDictionarysDto> responseDictionarysDtos = dictionarys.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Ok("数据已获取", new { data = responseDictionarysDtos, total = total });
        }
        public async Task<ResponseApiDto> GetSunDictionaryByDTId(int id)
        {
            List<Dictionary> dictionaries = await _serverRepository.dictionarysEFCore.Query(d => d.DDictionaryTypeId == id && d.DParentId == null).ToListAsync();
            List<ResponseDictionarysDto> responseDictionarysDtos = dictionaries.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Ok("数据已获取", responseDictionarysDtos);
        }

        public async Task<ResponseApiDto> GetSunDictionaryByParentId(int id)
        {
            List<Dictionary> dictionaries = await _serverRepository.dictionarysEFCore.Query(d => d.DParentId == id).ToListAsync();
            List<ResponseDictionarysDto> responseDictionarysDtos = dictionaries.Select(d => d.ToResponseDto()).ToList();
            return ResponseApiDto.Ok("数据已获取", responseDictionarysDtos);
        }

        public async Task<ResponseApiDto> GetDictionaryBySearchKey(string searchKey)
        {
            if (!await _serverRepository.dictionaryTypesEFCore.Query(d => d.DtKey == searchKey).AnyAsync())
            {
                return ResponseApiDto.Fail("该键值不存在");
            }
            int dtid = await _serverRepository.dictionaryTypesEFCore.Query(d => d.DtKey == searchKey).Select(d => d.DtId).SingleAsync();
            List<Dictionary> dictionaries = await _serverRepository.dictionarysEFCore.Query(d => d.DDictionaryTypeId == dtid).ToListAsync();
            return ResponseApiDto.Ok("数据已获取", _ListToTreeList(dictionaries.Where(d => d.DParentId == null).ToList(), dictionaries));
        }

        private List<ResponseDictionarysDto> _ListToTreeList(List<Dictionary> roots, List<Dictionary> list)
        {
            List<ResponseDictionarysDto> result = new List<ResponseDictionarysDto>();
            for (int i = 0; i < roots.Count; i++)
            {
                Dictionary root = roots[i];
                var r = root.ToResponseDto();
                List<Dictionary> children = list.Where(d => d.DParentId == root.DId).ToList();
                r.children = _ListToTreeList(children, list); 
                result.Add(r);
            }
            return result;
        }
    }
}